package com.wheat.vipcard.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Transaction;

import com.opensymphony.xwork2.ActionSupport;
import com.wheat.vipcard.bean.Zone;
import com.wheat.vipcard.bean.ZoneDAO;
import com.wheat.vipcard.utils.PageResultSet;
import com.wheat.vipcard.utils.PageUtil;

/**
 * 会员地区信息Action
 * 
 * @author JackLiang
 * @date 2014-1-12
 * @version 1.0
 */
public class ZoneAction extends ActionSupport {

	private static final Log LOG = LogFactory.getLog(ZoneAction.class);

	private HttpServletRequest request = null;
	private ZoneDAO zoneDAO = new ZoneDAO();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Zone zone;
	private String result;

	public Zone getZone() {
		return zone;
	}

	public void setZone(Zone zone) {
		this.zone = zone;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	/**
	 * ��ӵ���
	 * 
	 * @return
	 * @throws Exception
	 */
	public String saveZone() throws Exception {
		Transaction tx = zoneDAO.getSession().beginTransaction();
		System.out.println("name =" + zone);
		try {
			if (zone != null) {
				zoneDAO.save(zone);
				tx.commit();
			}
		} catch (Exception e) {
			if (tx.isActive()) {
				tx.rollback();
			}
			if (LOG.isErrorEnabled()) {
				LOG.error("System error!" + e);
			}
		} finally {
			zoneDAO.getSession().close();
		}
		return "saveZone";
	}

	/**
	 * 获取全部地区信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getAllZone() throws Exception {
		try {
			return SUCCESS;
		} catch (Exception e) {
			if (LOG.isErrorEnabled()) {
				LOG.error("System error!" + e);
			}
			e.printStackTrace();
		} finally {
			zoneDAO.getSession().close();
		}
		return ERROR;
	}

	/**
	 * 分页查询
	 * 
	 * @return
	 */
	public String listByPage() {
		request = ServletActionContext.getRequest();
		try {
			int sPage = Integer.valueOf((String) request.getParameter("page"));

			PageResultSet<Zone> pageResultSetList = zoneDAO.findZoneByPage(zone, sPage, new PageUtil().getPageSize());
			Map<String, Object> resultJsonMap = new HashMap<String, Object>();
			resultJsonMap.put("event", pageResultSetList.getList());
			resultJsonMap.put("pageBean", pageResultSetList.getPage());
			resultJsonMap.put("pageCount", pageResultSetList.getPage().getTotalPage());
			this.result = JSONObject.fromObject(resultJsonMap).toString();
			return SUCCESS;
		} catch (Exception e) {
			if (LOG.isErrorEnabled()) {
				LOG.error("System error!" + e);
			}
		} finally {
			zoneDAO.getSession().close();
		}
		return ERROR;
	}
}
